package com.wx.wx;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

@RestController
public class WxPubController {
    //token
    private String TOKEN = "mytestwechat";

    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String checkName(@RequestParam(name="signature") String signature,
                            @RequestParam(name="timestamp") String timestamp,
                            @RequestParam(name="nonce") String nonce,
                            @RequestParam(name = "echostr") String echostr) {
        System.out.println("--------------开始校验--------------");
        //sort
        String sortString = sort(TOKEN, timestamp, nonce);
        //lock
        String myString = sha1(sortString);
        //test
        if (myString != null && myString != "" && myString.equals(signature)) {
            System.out.println("签名验证通过");
            return echostr;
        } else {
            System.out.println("签名验证失败");
            return "";
        }
    }
    //sort
     private String sort(String token, String timestamp, String nonce) {
        String[] strArray = {token, timestamp, nonce};
        Arrays.sort(strArray);
        StringBuilder sb = new StringBuilder();
        for (String str : strArray) {
            sb.append(str);
        }
        return sb.toString();
    }

    private String sha1(String str) {
        try {
            MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(str.getBytes());
            byte messageDigest[] = digest.digest();
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
                if (shaHex.length() < 2) {
                    hexString.append(0);
                }
                hexString.append(shaHex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}

